<!-- 用户组页面 -->
<template>
  <div class="crowd-management-container">
    <!-- 顶部标题和新建按钮 -->
    <div class="header">
      <span class="title">信息管理</span>
      <el-button type="primary" class="add-button" @click="beforeAddCrowd">新建人群</el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true">
        <el-form-item label="人群名称">
          <el-input placeholder="请输入人群名称" v-model="searchForm.name"></el-input>
        </el-form-item>
        <el-form-item label="启动状态">
          <el-select placeholder="请选择状态" v-model="searchForm.status">
            <el-option label="全部" value=""></el-option>
            <el-option label="已启动" value="1"></el-option>
            <el-option label="未启动" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-date-picker
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD HH:mm:ss"
              format="YYYY-MM-DD HH:mm:ss"
              v-model="times"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="primary" @click="loadCrowdList">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 人群表格 -->
    <el-card class="table-card">
      <el-table :data="crowdList" border stripe>
        <el-table-column prop="id" label="编号" width="150" align="center"></el-table-column>
        <el-table-column prop="name" label="人群名称" width="150" align="center"></el-table-column>
        <el-table-column label="用户类型" width="150" align="center">
          <template #default="scope">
            <el-button type="text" @click="viewUserTypes(scope.row)">查看({{scope.row.userTypeCount}})</el-button>
          </template>
        </el-table-column>
        <el-table-column label="活动数量" width="150" align="center">
          <template #default="scope">
            <el-button type="text" @click="viewActivities(scope.row)">查看({{scope.row.activityCount}})</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="180">
          <template #default="scope">
            <el-switch
                v-model="scope.row.status"
                active-value="active"
                inactive-value="inactive"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button type="text" @click="editCrowd(scope.row)">编辑</el-button>
            <el-button type="text" @click="deleteCrowd(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
      </el-pagination>
    </el-card>

    <!-- 新建/编辑人群对话框 -->
    <el-dialog
        :title="dialogTitle"
        v-model="dialogVisible"
        width="50%"
        :before-close="handleClose"
    >
      <el-form :model="crowdForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="人群名称" required>
              <el-input v-model="crowdForm.name" placeholder="请输入人群名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="启动状态">
              <el-switch
                  v-model="crowdForm.status"
                  active-value="1"
                  inactive-value="0"
                  active-text="已启动"
                  inactive-text="未启动">
              </el-switch>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述">
          <el-input
              type="textarea"
              :rows="3"
              v-model="crowdForm.description"
              placeholder="请输入人群描述介绍">
          </el-input>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-tag
              v-for="type in crowdForm.userTypes"
              :key="type"
              closable
              @close="removeUserType(type)"
          >
            {{ type }}
          </el-tag>
          <el-input
              v-if="inputVisible"
              ref="typeInput"
              v-model="inputValue"
              size="small"
              @keyup.enter="addUserType"
              @blur="addUserType"
          />
          <el-button v-else size="small" @click="showInput">+ 添加用户类型</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="saveCrowd">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, nextTick, onMounted} from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

onMounted(()=>{
  ElMessage.success('加载成功')
})
// 人群列表数据
const crowdList = ref([
  {
    id: 45,
    name: '甜品制作师',
    userTypes: ['厨师', '甜品师'],
    userTypeCount: 260,
    activityCount: 5,
    description: '人群描述介绍',
    createTime: '2025-06-14 17:15:16',
    status: '1'
  },
  {
    id: 43,
    name: '美食集主',
    userTypes: ['美食博主', '厨师'],
    userTypeCount: 200,
    activityCount: 5,
    description: '人群描述介绍',
    createTime: '2025-06-14 17:15:16',
    status: '1'
  },
  {
    id: 42,
    name: '音乐粉丝',
    userTypes: ['流行音乐', '古典音乐'],
    userTypeCount: 670,
    activityCount: 5,
    description: '人群描述介绍',
    createTime: '2025-06-14 17:15:16',
    status: '1'
  },
  {
    id: 41,
    name: '健身女士',
    userTypes: ['健身爱好者', '女性用户'],
    userTypeCount: 252,
    activityCount: 5,
    description: '人群描述介绍',
    createTime: '2025-06-14 17:15:16',
    status: '1'
  },
  {
    id: 39,
    name: '旅游爱好者',
    userTypes: ['国内游', '国际游'],
    userTypeCount: 467,
    activityCount: 5,
    description: '人群描述介绍',
    createTime: '2025-06-14 17:15:16',
    status: '1'
  }
])

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

// 人群表单
const crowdForm = reactive({
  id: null,
  name: '',
  userTypes: [],
  userTypeCount: 0,
  activityCount: 5,
  description: '人群描述介绍',
  status: '1'
})

// 对话框控制
const dialogVisible = ref(false)
const dialogTitle = ref('新建人群')
const isEdit = ref(false)

// 用户类型相关
const inputVisible = ref(false)
const inputValue = ref('')
const typeInput = ref(null)

// 加载人群列表
const loadCrowdList = () => {
  // 实际项目中这里应该是API调用
  ElMessage.success('搜索成功')
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.status = ''
  loadCrowdList()
}

// 分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadCrowdList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadCrowdList()
}

// 准备添加人群
const beforeAddCrowd = () => {
  dialogTitle.value = '新建人群'
  isEdit.value = false
  Object.assign(crowdForm, {
    id: null,
    name: '',
    userTypes: [],
    userTypeCount: 0,
    activityCount: 5,
    description: '人群描述介绍',
    status: '1'
  })
  dialogVisible.value = true
}

// 编辑人群
const editCrowd = (row) => {
  dialogTitle.value = '编辑人群'
  isEdit.value = true
  Object.assign(crowdForm, JSON.parse(JSON.stringify(row)))
  dialogVisible.value = true
}

// 删除人群
const deleteCrowd = (id) => {
  ElMessageBox.confirm('确定要删除该人群吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中这里应该是API调用
    crowdList.value = crowdList.value.filter(crowd => crowd.id !== id)
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 查看用户类型
const viewUserTypes = (row) => {
  ElMessage.info(`人群 ${row.name} 的用户类型: ${row.userTypes.join(', ')}`)
}

// 查看活动
const viewActivities = (row) => {
  ElMessage.info(`正在查看人群 ${row.name} 的活动`)
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 保存人群
const saveCrowd = () => {
  if (!crowdForm.name) {
    ElMessage.warning('请填写人群名称')
    return
  }

  if (isEdit.value) {
    // 更新人群
    const index = crowdList.value.findIndex(crowd => crowd.id === crowdForm.id)
    if (index !== -1) {
      crowdList.value[index] = {
        ...crowdForm,
        userTypeCount: crowdForm.userTypes.length
      }
    }
    ElMessage.success('更新成功')
  } else {
    // 添加人群
    const newId = Math.max(...crowdList.value.map(crowd => crowd.id)) + 1
    crowdList.value.unshift({
      ...crowdForm,
      id: newId,
      userTypeCount: crowdForm.userTypes.length,
      createTime: new Date().toLocaleString()
    })
    ElMessage.success('添加成功')
  }
  dialogVisible.value = false
}

// 用户类型操作
const removeUserType = (type) => {
  crowdForm.userTypes = crowdForm.userTypes.filter(t => t !== type)
}

const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    typeInput.value.focus()
  })
}

const addUserType = () => {
  if (inputValue.value && !crowdForm.userTypes.includes(inputValue.value)) {
    crowdForm.userTypes.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>

<style scoped>
.crowd-management-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.header {
  height: 60px;
  padding: 10px 20px;
  background-color: #fff;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 20px;
  line-height: 60px;
}

.add-button {
  margin-top: 10px;
}

.search-card {
  margin-bottom: 10px;
}

.table-card {
  margin-bottom: 20px;
}

.el-tag {
  margin-right: 10px;
}

.pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>